package com.song.config;

import com.song.hanlder.MyAccessDenyHanlder;
import com.song.hanlder.MyAuthenticationFailureHandler;
import com.song.hanlder.MyAuthenticationSuccessHandler;
import com.song.hanlder.MyLogoutSuccessHanlder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author Klys
 * @Date 2023/6/5 15:10
 * @Description
 * @Version 1.0
 */
@Configuration
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //注入认证成功控制器
    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Autowired
    private MyLogoutSuccessHanlder myLogoutSuccessHanlder;
    @Autowired
    private MyAccessDenyHanlder myAccessDenyHanlder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/student/**").hasRole("student")
                .mvcMatchers("/pytest02", "/test").permitAll()
                .anyRequest().authenticated()

                .and()
                .formLogin()
                .permitAll()
                //设置认证成功处理器
                .successHandler(myAuthenticationSuccessHandler)
                //设置认证失败处理器
                .failureHandler(myAuthenticationFailureHandler)

                .and()
                .logout().logoutSuccessHandler(myLogoutSuccessHanlder)

                .and()
                .exceptionHandling().accessDeniedHandler(myAccessDenyHanlder);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {//定义编码器
        return new BCryptPasswordEncoder();
    }
}
